import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:provider/provider.dart';
import '../service/service_methods.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../routes/application.dart';
import '../provider/current_index.dart';
import '../provider/child_category.dart';
import '../provider/category_goods_list.dart';
import '../model/category.dart';
import '../model/categoryGoodsList.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  int page = 1;
  List<Map> hotGoodsList = [];

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _getGoodsData();
    print('初始化page页面数据......');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('百姓生活+'),
        ),
        body: FutureBuilder(
          future: request('homePageContext', formData: {'lon':'115.02932','lat':'35.76189'}),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              var data = json.decode(snapshot.data.toString());
              List<Map> swiperDataList =
                  (data['data']['slides'] as List).cast();
              List<Map> navigatorList =
                  (data['data']['category'] as List).cast();
              String advertesPicture = data['data']['advertesPicture']['PICTURE_ADDRESS'];
              String leaderImage = data['data']['shopInfo']['leaderImage'];
              String leaderPhone = data['data']['shopInfo']['leaderPhone'];
              List<Map> recommendList = (data['data']['recommend'] as List).cast();
              String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS'];
              String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS'];
              String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS'];
              List<Map> floor1 = (data['data']['floor1'] as List).cast();
              List<Map> floor2 = (data['data']['floor2'] as List).cast();
              List<Map> floor3 = (data['data']['floor3'] as List).cast();

              return EasyRefresh(
                child: ListView(
                  children: <Widget>[
                    SwiperDiy(
                      swiperDataList: swiperDataList,
                    ),
                    TopNavigator(navigatorList: navigatorList),
                    AdBanner(advertesPicture: advertesPicture,),
                    LeaderPhone(leaderImage: leaderImage, leaderPhone: leaderPhone,),
                    Recommand(recommendList: recommendList,),
                    FloorTitle(pictureAddress: floor1Title,),
                    FloorContent(floorGoodsList: floor1,),
                    FloorTitle(pictureAddress: floor2Title,),
                    FloorContent(floorGoodsList: floor2,),
                    FloorTitle(pictureAddress: floor3Title,),
                    FloorContent(floorGoodsList: floor3,),
                    _hotGoods()
                  ],
                ),
                onLoad: ()async{
                  print('开始加载更多...');
                  await _getGoodsData();
                },
                topBouncing: false,
                footer: ClassicalFooter(
                  noMoreText: '',
                  loadText: '上拉加载更多',
                  loadingText: '数据加载中...',
                  loadedText: '加载完成',
                  textColor: Colors.pink,
                  showInfo: false
                ),
              );
            } else {
              return Text('加载中');
            }
          },
        ),
      ),
    );
  }

  // 获取火爆专区数据
  Future _getGoodsData() async {
    var formPage = {'page': page};
    return request('homePageBelowConten', formData: formPage).then((val) {
      var data = json.decode(val.toString());
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
      });
    });
  }

  // 火爆专区标题
  Widget _hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    padding: EdgeInsets.all(5.0),
    alignment: Alignment.center,
    decoration: BoxDecoration(
      color: Colors.transparent,
      border: Border(
        bottom: BorderSide(width: 0.5, color: Colors.black12)
      ),
    ),
    child: Text('火爆专区'),
  );

  // 火爆专区流式布局
  Widget _wrapList() {
    if (hotGoodsList.length!=0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: (){
            Application.router.navigateTo(context, '/details?id=${val['goodsId']}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(val['image'], width: ScreenUtil().setWidth(375),),
                Text(
                  val['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${val['mallPrice']}'),
                    Text(
                      '￥${val['price']}', 
                      style: TextStyle(color: Colors.black26, decoration: TextDecoration.lineThrough),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('');
    }
  }

  // 火爆专区组合
  Widget _hotGoods() {
    return Container(
      child: Column(
       children: <Widget>[
         _hotTitle,
         _wrapList()
       ], 
      ),
    );
  }
}

// 轮播图
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;
  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setWidth(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount: swiperDataList.length,
        itemBuilder: (BuildContext context, int index) {
          return InkWell(
            child: Image.network(
              swiperDataList[index]['image'],
              fit: BoxFit.fill,
            ),
            onTap: (){
              Application.router.navigateTo(context, '/details?id=${swiperDataList[index]['goodsId']}');
            },
          );
        },
        pagination: new SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

// 导航区域
class TopNavigator extends StatelessWidget {
  final List navigatorList;
  TopNavigator({Key key, this.navigatorList}) : super(key: key);

  Widget _gridItemView(BuildContext context, item) {
    return InkWell(
      onTap: () async {
        Provider.of<CurrentIndexProvider>(context, listen: false).changIndex(1);
        List<BxMallSubDto> list = CategoryBigModel.fromJson(item).bxMallSubDto;
        Provider.of<ChildCategory>(context, listen: false).updateChildCategoryList(list, item['mallCategoryId']);
        _getGoodsList(item['mallCategoryId'], context);
      },
      child: Column(
        children: <Widget>[
          Image.network(
            item['image'],
            width: ScreenUtil().setWidth(95),
          ),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }

  void _getGoodsList(String categorySubId, context) {
    var data = {
      'categoryId': Provider.of<ChildCategory>(context, listen: false).categoryId,
      'categorySubId': Provider.of<ChildCategory>(context, listen: false).subId,
      'page': Provider.of<ChildCategory>(context, listen: false).page
    };
    request('getMallGoods', formData: data).then((val){
      var data = json.decode(val.toString());
      // setState(() {
      //   list = CategoryGoodsListModel.fromJson(data).data;
      // });
      // 存储到provider
      Provider.of<CategoryGoodsListProvider>(context, listen: false).changeCategoryGoodsList(CategoryGoodsListModel.fromJson(data).data);
      // print('商品列表数据：$data');
    });
  }

  @override
  Widget build(BuildContext context) {
    if (navigatorList.length > 10) {
      navigatorList.removeRange(10, navigatorList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: navigatorList.map((item) {
          return _gridItemView(context, item);
        }).toList(),
      ),
    );
  }
}

// 广告图片
class AdBanner extends StatelessWidget {
  final String advertesPicture;
  const AdBanner({Key key, this.advertesPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(advertesPicture),
    );
  }
}

// 拨打电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderImage;
  final String leaderPhone;
  const LeaderPhone({Key key, this.leaderImage, this.leaderPhone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: _launchPhone,
        child: Image.network(leaderImage),
      ),
    );
  }

  void _launchPhone() async{
    String url = 'tel:$leaderPhone';
    if (await canLaunch(url) ) {
      await launch(url);
    } else {
      throw "电话不正确！";
    }
  }
}

// 商品推荐
class Recommand extends StatelessWidget {
  final List recommendList;
  const Recommand({Key key, this.recommendList}) : super(key: key);

  // 推荐页标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5, color: Colors.black12)
        ),
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(
          color: Colors.pink
        ),
      ),
    );
  }

  // 商品单项
  Widget _item(context, int index) {
    return InkWell(
      onTap: (){
        Application.router.navigateTo(context, '/details?id=${recommendList[index]['goodsId']}');
      },
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(left: BorderSide(width: 0.5, color: Colors.black12))
        ),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('￥${recommendList[index]["mallPrice"]}'),
            Text(
              '￥${recommendList[index]["price"]}',
              style: TextStyle(
                decoration: TextDecoration.lineThrough,
                color: Colors.grey
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(330),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index){
          return _item(context, index);
        },
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(380),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[
          _titleWidget(),
          _recommendList()
        ],
      ),
    );
  }
}

// 楼层区域标题的编写
class FloorTitle extends StatelessWidget {
  final String pictureAddress;
  const FloorTitle({Key key, this.pictureAddress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(pictureAddress),
    );
  }
}

// 楼层商品组件
class FloorContent extends StatelessWidget {
  final List floorGoodsList;
  const FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(context),
          _otherGoods(context)
        ],
      ),
    );
  }

  Widget _firstRow(context){
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context, floorGoodsList[1]),
            _goodsItem(context, floorGoodsList[2]),
          ],
        ),
      ],
    );
  }

  Widget _otherGoods(context){
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodsList[3]),
        _goodsItem(context, floorGoodsList[4]),
      ],
    );
  }

  Widget _goodsItem(context, Map goods){
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: (){
          Application.router.navigateTo(context, '/details?id=${goods['goodsId']}');
        },
        child: Image.network(goods['image']),
      ),
    );
  }
}